package com.vm.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.vm.commons.CurrentUser;
import com.vm.commons.VMConst;
import com.vm.model.Comment;
import com.vm.model.Soft;
import com.vm.myview.ViewUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;

@SuppressLint("InflateParams")
public class SoftCommentsFragment extends BaseFragment {
	protected static final String TAG = null;
	private View view;
	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;
	TextView tv_score;
	RatingBar rb_star;
	TextView tv_comments_num;
	RelativeLayout rl_comment;
	// private RequestQueue mQueue;
	Soft soft;
	String currentId;
	LinearLayout found_ll_1;
	boolean canRequest = false;
	ViewUtils viewUtils;
	Dialog dialog;
	RatingBar ratingBar;
	EditText et_content;
	ScrollView sv;
	int pageNow = 1;

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
				mainHandler.sendMessage(new Message());
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(300);

					// 在这里添加调用接口获取数据的代码
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					// setView();
					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				UIHelper.hideDialogForLoading();
			}
		}.execute();
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("CategoryGameFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.comments, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		isPrepared = true;
		lazyLoad();

	}

	private void initData() {
		viewUtils = new ViewUtils(getActivity());
		RequestQueue mQueue = MyVolley.getRequestQueue();
		soft = (Soft) getArguments().get("soft");
		currentId = soft.getId();
		if (soft.getStar() != null) {
			float fstar = soft.getStar();
			tv_score.setText(Float.toString(fstar / 2));
			rb_star.setRating(fstar / 2);
		}
		String url = VMConst.REQUEST_URL + "getComment?softId=" + currentId;
		JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						// TODO Auto-generated method stub
						found_ll_1.removeAllViews();
						tv_comments_num.setText(Integer.toString(arg0.length()));
						for (int i = 0; i < arg0.length(); i++) {
							if (arg0.length() == 10) {
								canRequest = true;
							}
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								Comment comment = JsonUtils.jsonToBean(
										jsonObject, Comment.class);
								if (comment != null) {
									found_ll_1.addView(viewUtils.dyAddView4(i,
											comment));
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);
	}

	public void initView() {
		tv_score = (TextView) view.findViewById(R.id.tv_score);
		rb_star = (RatingBar) view.findViewById(R.id.rb_star);
		tv_comments_num = (TextView) view.findViewById(R.id.tv_comments_num);
		rl_comment = (RelativeLayout) view.findViewById(R.id.rl_comment);
		rl_comment.setOnClickListener(publishListener);
		found_ll_1 = (LinearLayout) view.findViewById(R.id.found_ll_1);
		sv = (ScrollView) view.findViewById(R.id.sv);
		sv.setOnTouchListener(new TouchListenerImpl());
		initData();
	}

	OnClickListener publishListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (CurrentUser.USERID != null) {
				RequestQueue mQueue = MyVolley.getRequestQueue();
				// TODO Auto-generated method stub
				String url = VMConst.REQUEST_URL + "ifPublishComment?userId="
						+ CurrentUser.USERID + "&softId=" + currentId;
				StringRequest addCommentRequest = new StringRequest(url,
						new Listener<String>() {

							@Override
							public void onResponse(String response) {
								if (response.contains("1")) {

									Toast toast = Toast.makeText(getActivity(),
											"不能重复评论", Toast.LENGTH_SHORT);
									toast.show();
								} else {
									String url = VMConst.REQUEST_URL
											+ "ifDown?userId="
											+ CurrentUser.USERID + "&softId="
											+ currentId;
									RequestQueue rQueue = MyVolley
											.getRequestQueue();
									StringRequest ifDownRequest = new StringRequest(
											url, new Listener<String>() {

												@Override
												public void onResponse(
														String arg0) {
													// TODO Auto-generated
													// method
													// stub
													if (arg0.contains("1")) {
														openDialog();
													} else {
														Toast toast = Toast
																.makeText(
																		getActivity(),
																		"必须下载安装该应用才能发表评论",
																		Toast.LENGTH_SHORT);
														toast.show();
													}
												}
											}, null);
									rQueue.add(ifDownRequest);

								}
							}
						}, new ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {
								Toast toast = Toast.makeText(getActivity(),
										"提交失败", Toast.LENGTH_SHORT);
								toast.show();
							}
						});

				mQueue.add(addCommentRequest);

			} else {
				Toast toast = Toast.makeText(getActivity(), "登陆后才能发表评论哦",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	};

	private void openDialog() {
		// View menuView = null;
		View menuView = View.inflate(getActivity(),
				R.layout.published_comments, null);

		dialog = new Dialog(getActivity(), R.style.dialog);

		dialog.setContentView(menuView);
		dialog.show();

		ratingBar = (RatingBar) menuView.findViewById(R.id.ratingBar1);
		et_content = (EditText) menuView.findViewById(R.id.et_comments);
		Button btn_cancel = (Button) menuView.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(menuClickListener);
		Button btn_confirm = (Button) menuView.findViewById(R.id.btn_confirm);
		btn_confirm.setOnClickListener(menuClickListener);

	}

	OnClickListener menuClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			RequestQueue mQueue = MyVolley.getRequestQueue();
			switch (v.getId()) {
			case R.id.btn_confirm:
				float fstar = ratingBar.getRating() * 2;

				String star = Integer.toString((int) fstar);
				String content = et_content.getText().toString();
				try {
					content = URLEncoder.encode(content, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				String url = VMConst.REQUEST_URL + "addComment?userId="
						+ CurrentUser.USERID + "&username="
						+ CurrentUser.USERNAME + "&softId=" + currentId
						+ "&content=" + content + "&star=" + star;
				StringRequest addCommentRequest = new StringRequest(url,
						new Listener<String>() {

							@Override
							public void onResponse(String response) {
								if (response.contains("1")) {
									dialog.cancel();
									Toast toast = Toast.makeText(getActivity(),
											"提交成功", Toast.LENGTH_SHORT);
									toast.show();
									initData();
								} else {
									dialog.cancel();
									Toast toast = Toast.makeText(getActivity(),
											"提交失败", Toast.LENGTH_SHORT);
									toast.show();

								}
							}
						}, new ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {
								Toast toast = Toast.makeText(getActivity(),
										"提交失败", Toast.LENGTH_SHORT);
								toast.show();
							}
						});

				mQueue.add(addCommentRequest);

				break;
			case R.id.btn_cancel:
				dialog.cancel();
				break;

			default:
				break;
			}
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			initView();
		};
	};

	@SuppressLint("ClickableViewAccessibility")
	private class TouchListenerImpl implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = v.getScrollY();
				int height = v.getHeight();
				int scrollViewMeasuredHeight = sv.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {
					if (canRequest) {
						canRequest = false;
						System.out.print("canRequest:" + canRequest);
						pageNow++;
						System.out.print("pageNow:" + pageNow);
						RequestQueue mQueue = MyVolley.getRequestQueue();
						String url = VMConst.REQUEST_URL + "getComment?softId="
								+ currentId + "&pageNum=" + pageNow;
						JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(
								url, new Listener<JSONArray>() {
									@Override
									public void onResponse(JSONArray arg0) {
										// TODO Auto-generated method stub
										for (int i = 0; i < arg0.length(); i++) {
											if (arg0.length() == 10) {
												canRequest = true;
											}
											try {
												JSONObject jsonObject = arg0
														.getJSONObject(i);
												Comment comment = JsonUtils
														.jsonToBean(jsonObject,
																Comment.class);
												if (comment != null) {
													found_ll_1.addView(viewUtils
															.dyAddView4(i,
																	comment));
												}
											} catch (JSONException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
										}
									}

								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										Log.e(TAG, error.getMessage(), error);
									}
								});
						mQueue.add(jsonObjectRequest);
					}
				}
				break;
			}
			return false;
		}

	}
}